/*
 * @Date         : 2024-05-20 13:35:06 星期1
 * @Author       : xut
 * @Description  :
 */
import { z } from "zod"
import type { Request, Response, NextFunction } from "express"

export function zodSchemaValidate(schema: z.AnyZodObject) {
  return async function validateMiddle(
    req: Request,
    res: Response,
    next: NextFunction
  ) {
    try {
      schema.parse({ params: req.params, query: req.query, body: req.body })
      next()
    } catch (err: any) {
      if (err instanceof z.ZodError) {
        return res.status(400).json({
          status: "fail",
          message: err.message,
        })
      }
      return res.status(500).json({
        status: "error",
        message: err.message,
      })
    }
  }
}
